<template>
	<view class="container">
		<z-paging ref="paging" refresher-only @onRefresh="onRefresh" @scrolltolower="handleScrollBottom">
			<!-- 页面内容 -->
			<view class="" slot="top">
				<view class="header">
					<view class="">
						<text class="text-bold f-s28 line-height40">报名</text>
					</view>
					<view class="tag">
						<view class="tag-item" v-for="(item,index) in tagList" :key="index"
							@click="handleTagChange(item,index)" :class="{'tag-active':index === tagCurrent}">
							<text>{{item.text}}</text>
						</view>
					</view>

				</view>
			</view>

			<view class="main">

				<view class="card">
					<view class="card-item" v-for="(item,index) in list" :key="item.id" @click="handleToPage(item.id)">
						<view class="flex full-width overflow-hidden">
							<image :src="item.service_data.cover" class="cover shrink-0" mode=""></image>
							<view class="m-l12 flex-1 overflow-hidden">
								<view class="flex justify-between align-center">
									<view class="flex align-center overflow-hidden">
										<text
											class="text-bold f-s15 line-height22 text-cut overflow-hidden">{{item.service_name}}</text>
										<image src="/static/images/signup/vip.png"
											class="width-23 height-16 shrink-0 m-l2" mode=""
											v-if="(item.publish_user_data && item.publish_user_data.is_vip) == 1">
										</image>
									</view>
									<view class="flex align-center shrink-0">
										<image src="/static/images/signup/location-1.png"
											class="width-16 height-16 m-r4" mode=""></image>
										<text class="line-height16 f-w500 f-s12">距{{item.distance}}km</text>
									</view>
								</view>
								<view class="m-t8 card-tags">
									<view class="card-item-tag"
										v-for="(tagItem,tagIndex) in item.remark_tags.split(',')" :key="tagIndex">
										<text>{{tagItem}}</text>
									</view>
								</view>
								<view class="m-t18">
									<!-- <text
										class="f-s14 text-bold text-theme line-height18">￥{{item.service_price}}</text>
									<text class="text-gray f-s12">/人</text>
									<text class="p-l6 text-gray f-s12 m-l6">时长{{item.activity_duration}}小时</text> -->
									<text class="text-theme">报名参与</text>
								</view>
							</view>
						</view>
						<view class="m-t14 flex justify-between">
							<view class="flex flex-direction justify-between overflow-hidden">
								<view class="flex align-center">
									<image src="/static/images/signup/time.png" class="width-16 height-16 m-r8" mode="">
									</image>
									<text
										class="f-s12 f-w400">期望{{formatArriveTime(item.appointment_arrive_time)}}到达</text>
								</view>
								<view class="flex align-center overflow-hidden">
									<image src="/static/images/signup/location.png" class="width-16 height-16 m-r8"
										mode="">
									</image>
									<text class="f-s12 f-w400 text-cut overflow-hidden">{{item.address}}</text>
								</view>
							</view>
							<view class="" @click.stop v-if="item.apply_status == 0 && queryParams.apply_type === 1">
								<view class="card-item-btn shrink-0 flex flex-direction" @click="handleToPage(item.id)">
									<text class="f-s12 f-w500 line-height16">立即报名</text>
									<view class="f-s11 f-w400 flex justify-center align-center">
										<u-count-down :time="handleCutOffTime(item.end_apply_time)"
											format="HH:mm:ss" class="count-down"
											@finish="handleCutOffTimeFinish(index)"></u-count-down>
										<text class="m-l2">截止</text>
									</view>
								</view>
							</view>

							<view class="" @click.stop
								v-if="item.apply_status == 1 && !handleCancelTimeCheck(item.can_cancel_time)">
								<view class="card-item-btn shrink-0" :class="btnClassMap[0]">
									<text class="f-s12 f-w500 line-height16">已报名</text>
									<view class="f-s11 f-w400 flex justify-center align-center">
										<u-count-down :time="handleCancelTime(item.can_cancel_time)" format="mm:ss"
											class="count-down" @finish="handleCancelTimeFinish(index)"></u-count-down>
										<text class="m-l2">后可取消</text>
									</view>
								</view>
							</view>
							<view class="" @click.stop
								v-if="item.apply_status == 1 && handleCancelTimeCheck(item.can_cancel_time)">
								<view class="card-item-btn shrink-0" :class="btnClassMap[1]"
									@click="handleCancelSignup(item,index)">
									<text class="f-s12 f-w500 line-height16">取消报名</text>
								</view>
							</view>
							<view class="" @click.stop v-if="item.apply_status == 2">
								<view class="card-item-btn shrink-0" :class="btnClassMap[0]">
									<text class="f-s12 f-w500 line-height16">未选中</text>
								</view>
							</view>
							<view class="" @click.stop v-if="item.apply_status == -1">
								<view class="card-item-btn shrink-0" :class="btnClassMap[0]">
									<text class="f-s12 f-w500 line-height16">已取消报名</text>
								</view>
							</view>
							<view class="" @click.stop v-if="item.apply_status == -2">
								<view class="card-item-btn shrink-0" :class="btnClassMap[0]">
									<text class="f-s12 f-w500 line-height16">已取消</text>
								</view>
							</view>
							<view class="" @click.stop v-if="item.apply_status == 5">
								<view class="card-item-btn shrink-0" :class="btnClassMap[0]">
									<text class="f-s12 f-w500 line-height16">已过期</text>
									<text class="f-s11 f-w400">报名已结束</text>
								</view>
							</view>
							<view class="" @click.stop v-if="item.apply_status == 3">
								<view class="card-item-btn shrink-0" :class="btnClassMap[1]">
									<text class="f-s12 f-w500 line-height16">已选中</text>
								</view>
							</view>
							<view class="" @click.stop v-if="item.apply_status == 4">
								<view class="card-item-btn shrink-0" :class="btnClassMap[1]">
									<text class="f-s12 f-w500 line-height16">已合作</text>
								</view>
							</view>
						</view>
					</view>

					<view class="padding-tb-xs" v-if="total !== 0">
						<u-loadmore :status="loadmoreStatus" line @loadmore="handleScrollBottom" />
					</view>
					<Empty :show="total === 0"></Empty>
				</view>
			</view>
		</z-paging>
		<Modal :show.sync="modalShow" content="你确认要取消本次项目的报名吗？" @confirm="hancleCancelSignUpConfirm"></Modal>
	</view>
</template>

<script>
	import Modal from "@/components/modal/index.vue"
	import dayjs from "dayjs"
	import {
		list,
		signUpCancel
	} from "@/api/signup/index.js"
	import mixins from "@/mixins";
	import {
		mapState
	} from 'vuex'
	export default {
		components: {
			Modal
		},
		mixins: [mixins],
		data() {
			return {
				cancelIndex: 0, // 取消报名索引
				// 取消报名传参
				cancelForm: {},
				list: [],
				queryParams: {
					lat: '',
					lng: '',
					apply_type: 1, // 1=未报名,2=已报名,3=已过期,默认0 全部
					page: 1,
					limit: 10
				},
				modalShow: false,
				btnClassMap: {
					0: 'disabled',
					1: 'cancel',
				},
				tagCurrent: 0,
				tagList: [{
					text: "待报名",
					value: 1
				}, {
					text: "已报名",
					value: 2
				}, {
					text: "已取消",
					value: 3
				}, {
					text: "未选中",
					value: 4
				}, {
					text: "已过期",
					value: 5
				}]
			}
		},
		onLoad() {
			this.getList()
		},
		onUnload() {
			uni.$off('operation', this.handleEmitDetail)
		},
		computed: {
			...mapState({
				positionInfo: state => state.user.position || {}
			})
		},
		methods: {
			// 下拉刷新被触发
			onRefresh() {
				this.queryParams.page = 1
				this.getList('scroll')
			},
			// 取消报名
			hancleCancelSignUpConfirm() {
				signUpCancel(this.cancelForm).then(res => {
					this.$toast("已取消")
					// 从列表中移除该数据
					this.list.splice(this.cancelIndex, 1)
				})
			},
			// 等待报名取消倒计时结束，可以取消报名
			handleCancelTimeFinish(index) {
				// 更新该数据项
				let item = this.list[index]
				this.list.splice(index, 1, item)
			},
			// 处理取消报名时间
			handleCancelTime(timestamp) {
				timestamp *= 1000
				// 可取消报名的时间 - 当前时间 = 剩余可取消报名时间
				return dayjs(timestamp).valueOf() - dayjs().valueOf()
			},
			// 检验是否可取消报名
			handleCancelTimeCheck(timestamp) {
				timestamp *= 1000
				// 当前时间是否在可取消时间之后
				return dayjs().isAfter(dayjs(timestamp))
			},
			// 截止报名时间倒计时结束，报名已过期
			handleCutOffTimeFinish(index) {
				// 从待报名列表中移除该项
				this.list.splice(index, 1)
				// 没有数据手动将total改为0 展示空数据图片
				if (this.list.length === 0) this.total = 0
			},
			// 处理截止报名时间
			handleCutOffTime(timestamp) {
				timestamp *= 1000
				// 处理错误情况，当前时间在截止时间之后，返回空字符
				if (dayjs().isAfter(dayjs(timestamp))) return ''
				// 截止报名时间 - 当前时间 = 剩余截止倒计时时间
				return dayjs(timestamp).valueOf() - dayjs().valueOf()
			},
			// 到达时间格式化
			formatArriveTime(timestamp) {
				return dayjs(timestamp*1000).format("M月D日 H:mm")
			},
			formatTime(minutes) {
				if (minutes < 60) {
					// 如果未超过60分钟，直接显示分钟
					return `${minutes}分钟`;
				} else {
					// 如果超过60分钟，转换为 "时:分" 格式
					const hours = Math.floor(minutes / 60); // 计算小时
					const remainingMinutes = minutes % 60; // 计算剩余的分钟
					return `${hours}小时${remainingMinutes}分钟`;
				}
			},
			getList(type) {
				let {
					lat,
					lng
				} = this.positionInfo
				this.queryParams.lat = lat
				this.queryParams.lng = lng
				this.loadmoreStatus = 'loading'
				list(this.queryParams).then(res => {
					// 使用了下拉刷新，获取到数据更新加载状态
					if(type === 'scroll'){
						this.$refs.paging.complete();
					}
					let {
						data: {
							list,
							count,
							total
						}
					} = res
					this.total = count
					this.pageTotal = total
					if (this.queryParams.page === this.pageTotal) this.loadmoreStatus = 'nomore'
					if (this.queryParams.page === 1) {
						this.list = list
					} else if (this.queryParams.page < this.pageTotal) {
						this.list = this.list.concat(list)
					}
				}).catch(()=>{
					if(type === 'scroll'){
						this.$refs.paging.complete();
					}
				})
			},
			handleTagChange(select, index) {
				this.list = []
				this.queryParams.page = 1
				this.queryParams.apply_type = select['value']
				this.tagCurrent = index
				this.getList()
			},
			handleCancelSignup(select, index) {
				this.cancelIndex = index
				this.cancelForm.id = select.id
				this.modalShow = true
			},
			// 详情页操作回调
			handleEmitDetail(raw) {
				if (raw.type == 'sign' || raw.type === 'cancel') {
					let findIndex = this.list.findIndex(item => item.id === raw.id)
					// 报名或取消报名操作，从列表中移除
					this.list.splice(findIndex, 1)
					// 重新检查数据数量
					this.total = this.list.length
				}
			},
			handleToPage(id) {
				// 监听详情操作
				uni.$on('operation', this.handleEmitDetail)
				this.$tab.navigateTo('detail?id=' + id)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.m-l2 {
		margin-left: 4rpx;
	}

	.container {
		background-color: inherit;

		.header {
			background-color: inherit;
			z-index: 99;
			position: sticky;
			top: 0;
			padding: 0 32rpx;
			padding-top: calc(var(--status-bar-height) + 36rpx);

			.tag {
				margin: 24rpx 0;
				display: flex;

				.tag-item {
					width: 136rpx;
					height: 64rpx;
					background-color: #FFFFFF;
					border-radius: 32rpx;
					font-weight: 400;
					font-size: 24rpx;
					line-height: 64rpx;
					text-align: center;
					margin-right: 20rpx;
					margin-bottom: 20rpx;
				}

				.tag-active {
					background-color: #202020;
					color: #fff;
				}
			}
		}

		.main {
			padding: 0 32rpx 36rpx 32rpx;

			.card {
				.card-item {
					border-radius: 20rpx;
					padding: 20rpx;
					background-color: #fff;
					margin-bottom: 20rpx;

					::v-deep .count-down {
						.u-count-down__text {
							font-weight: 400;
							font-size: 22rpx;
							color: #FFFFFF;
							line-height: 32rpx;
						}
					}

					.cover {
						width: 176rpx;
						height: 176rpx;
						background: #D8D8D8;
						border-radius: 16rpx;
						flex-shrink: 0;
					}

					.card-tags {
						// display: grid;
						// grid-auto-flow: dense;
						// gap: 10px;
						display: flex;
						flex-wrap: wrap;
						margin-bottom: -10rpx;

						/* 控制行和列的间距 */
						.card-item-tag {
							border-radius: 4rpx;
							border: 1rpx solid #FE3F59;
							font-size: 22rpx;
							color: #FE3F59;
							line-height: 32rpx;
							padding: 0 6rpx;
							margin-right: 20rpx;
							margin-bottom: 10rpx;
							// &:last-line{
							// 	margin-top: 10px;
							// }
						}
					}


					.card-item-btn {
						width: 168rpx;
						height: 72rpx;
						// padding: 6rpx 16rpx;
						background: #222222;
						border-radius: 12rpx;
						color: #FFFFFF;
						text-align: center;
						display: flex;
						flex-direction: column;
						justify-content: center;
					}

					.disabled {
						pointer-events: none;
						background: #B2B8C1;
						color: #FFFFFF;
					}

					.cancel {
						background: #FE3F59;
						color: #FFFFFF;
					}
				}
			}
		}
	}
</style>